/*
 * @Author: huangwei
 * @Date: 2021-06-30 10:56:36
 * @LastEditors: 黄威
 * @LastEditTime: 2022-03-04 10:35:39
 * @Description: 数组相关方法
 */

import L from 'leaflet'
import * as Cesium from 'Cesium'

// 坐标转坐标数组
export function toArray(type: string, data: any): any[] | void {
    if (!Array.isArray(data) || data.length === 0) return

    try {
        if (type === 'Point' || type === 'Model') {
            // [1, 2] or [[1, 2], [3, 4]]
            if (!Array.isArray(data[0])) return [data]
            return data
        } else if (type === 'Polyline') {
            // [[1,2], [2,3]] or [[[1,2], [2,3]], [[4,5], [2,3]]]
            if (!Array.isArray(data[0][0])) return [data]
            return data
        } else if (type === 'Polygon') {
            // [[1,2], [2,3]]
            if (!Array.isArray(data[0][0])) return [[data]]
            // [[[1,2], [2,3]]]
            if (!Array.isArray(data[0][0][0])) return [data]
            // [[[1,2], [2,3]], [holes1, holes2]], ...]
            return data
        } else {
            return [data]
        }
    } catch {
        return
    }
}

// 坐标重复判断
export function equeals(
    coord1: [number, number, number?],
    coord2: [number, number, number?]
) {
    return (
        coord1 &&
        coord2 &&
        coord1[0] === coord2[0] &&
        coord1[1] === coord2[1] &&
        coord1[2] === coord2[2]
    )
}

// 构造二维坐标
export function coordsToLLs(coords: [number, number][]): L.LatLng[] {
    return coords.map(coord => {
        return new L.LatLng(coord[1], coord[0])
    })
}

// 事件坐标转三维经纬度
export function cartesianToLL(position: Cesium.Cartesian3) {
    const cartographicPosition = Cesium.Cartographic.fromCartesian(position)
    const lng = Cesium.Math.toDegrees(cartographicPosition.longitude)
    const lat = Cesium.Math.toDegrees(cartographicPosition.latitude)

    return [lng, lat, cartographicPosition.height]
}

// 构造三维坐标
export function coordsToC3s(coords: [number, number][]) {
    return coords.map(coord => Cesium.Cartesian3.fromDegrees(...coord))
}

// 返回一个包裹后的坐标点
export function wrap(ll: [number, number, number?]) {
    const wrapll = new L.LatLng(ll[1], ll[0]).wrap()
    const wrapLLArr = [wrapll.lng, wrapll.lat]

    if (ll[2] !== undefined) {
        wrapLLArr[2] = ll[2]
    }
    Object.defineProperty(wrapLLArr, '_origin_coord_', { value: ll })
    return wrapLLArr
}
